import {defineStore} from 'pinia'
import {computed, ref} from "vue";
import {userUpload, userGetTable, userUpdateTable, userSubmitIdValidate, userUploadTable} from "@/apis/UserApi";
import {ElMessage} from 'element-plus';


export const useUserStore = defineStore('user', () => {
        const submitIdList = ref([])
        const classTable = ref(null)
        const submitId = ref('')


        // 修改课程表存储再本地的值
        const setTable = (table) => {
            classTable.value = table
        }

        // 新增提交id列表
        const setSubmitIdList = (submitId) => {
            if (!submitIdList.value.includes(submitId)) {
                // console.log(idList)
                submitIdList.value.unshift(submitId);
                // console.log(submitIdList.value)
            }
        }

        // 解析提交ID 并且把数据解析升一个展示用的数据
        const submitIdListShow = computed(() => {
            return submitIdList.value.map((submitId) => {
                let ALPHABET = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                // 获取时间戳的密文
                let encodedPart = submitId.substring(0, 7);
                // 初始化解码后的时间戳
                let timestamp = 0;
                // 遍历编码部分的每个字符，进行解码
                for (let char of encodedPart) {
                    // 找到字符在ALPHABET中的位置（_对应0）
                    let index = ALPHABET.indexOf(char); // +1是因为数组索引从0开始而ALPHABET中_代表0
                    if (index > 0) { // 确保字符有效
                        timestamp = timestamp * 26 + index;
                    }
                }

                // 将解码后的时间戳转换为日期字符串
                let date = new Date(timestamp * 1000); // 时间戳可能需要乘以1000转换为毫秒级
                let formattedDate = date.toLocaleString(); // 或使用其他格式化函数如Intl.DateTimeFormat等

                return {
                    name: formattedDate,
                    submitId: submitId
                }
            })
        })


        // 上传课程表
        const uploadTable = async (userId, userName, file, callback, finallyCb) => {
            // console.log('userStores：userId', userId, 'userName', userName, 'file', file);
            await userUpload(userId, userName, file).then(res => {
                // console.log('请求出来的课程表数据', res);
                // rota.value = res.data.course;
                    setTable(res.data.course)
                    submitId.value = res.data.submitId
                    setSubmitIdList(res.data.submitId)
                if (res.code === 1) {
                    ElMessage.success("上传成功")
                }
                if (res.code === 2) {
                    ElMessage(
                        {
                            type: 'warning',
                            message: res.msg,
                            duration: 0,
                            showClose: true,
                        }
                    )
                }
                callback()
            }).finally(() => finallyCb && finallyCb());
        }

        // 获取课程表
        const getTable = async (id) => {
            submitId.value = id
            userGetTable(id).then(res => {
                // console.log('请求课程表数据', res.code)

                if (res.code === 1) {
                    setTable(res.data.course)
                    ElMessage.success("获取成功")
                }

            })
        }

        // 修改课程表
        const updateTable = (id, x, y) => {
            let data = classTable.value
            // console.log(data)
            if (classTable.value[x][y] === '有课') {
                // console.log('有课')
                data[x][y] = ''
            } else {
                // console.log('没课')
                data[x][y] = '有课'
            }
            userUpdateTable(id.value, data).then(() => {
                ElMessage.success("更新成功")
                setTable(data);
            })
        }

        // 验证提交信息ID的合法性
        const submitIdValidate = () => {
            const validateInfo = ref()
            if ( submitIdList.value.length !== 0 ) {
                userSubmitIdValidate(submitIdList).then(res => {
                    validateInfo.value = res.data
                    for (let i = 0; i < validateInfo.value.length; i++) {
                        // 如果valid为false
                        if (!validateInfo.value[i].valid) {
                            // 从keys中移除对应的密钥
                            let index = submitIdList.value.indexOf(validateInfo.value[i].submitId);
                            if (index !== -1) {
                                submitIdList.value.splice(index, 1);
                            }
                        }
                    }
                })
            }
        }

        // 上传一个空的二维表格作为值班表
        const uploadEmptyTable = async (userId, userName, callback, finallyCb) => {
            const nullTable = [
                ['', '', '', '', ''],
                ['', '', '', '', ''],
                ['', '', '', '', ''],
                ['', '', '', '', ''],
                ['', '', '', '', '']
            ]
            await userUploadTable(userId, nullTable, userName).then(res => {
                // console.log('请求出来的课程表数据', res);
                // rota.value = res.data.course;
                if (res.code === 1) {
                    setTable(res.data.course)
                    submitId.value = res.data.submitId
                    setSubmitIdList(res.data.submitId)
                    ElMessage.success("空表格上传成功")
                }
                callback()
            }).finally(() => finallyCb && finallyCb());
        }


        return {
            submitId,
            submitIdList,
            submitIdListShow,
            classTable,
            getTable,
            setTable,
            uploadTable,
            updateTable,
            setSubmitIdList,
            submitIdValidate,
            uploadEmptyTable
        }
    },
    {
        persist: {
            storage: localStorage,
            paths: ['submitIdList', 'submitId'],
        },
    }
)
